package com.yning.coroutines.demo

import cn.youngning.coroutinedemo.model.Banner
import com.yning.coroutines.Log
import kotlinx.coroutines.*
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

suspend fun main() {
    Log.d("1")
    try {
        supervisorScope { //①
            Log.d("2")
            launch { // ②
                Log.d("3")
                launch { // ③
                    Log.d("4")
                    delay(100)
                    throw ArithmeticException("Hey!!")
                }
                Log.d("5")
            }
            Log.d("6")
            val job = launch { // ④
                Log.d("7")
                delay(1000)
            }
            try {
                Log.d("8")
                job.join()
                Log.d("9")
            } catch (e: Exception) {
                Log.d("10. $e")
            }
        }
        Log.d("11")
    } catch (e: Exception) {
        Log.d("12. $e")
    }
    Log.d("13")
}

@ExperimentalCoroutinesApi
suspend fun getUserCoroutine() = suspendCancellableCoroutine<Banner> { coroutine->
    val call = OkHttpClient().newCall(
            Request.Builder()
                    .get().url("https://api.github.com/users/bennyhuo")
                    .build())
    coroutine.invokeOnCancellation {
        log("invokeOnCancellation: cancel the request.")
        call.cancel()
    }

    /*call.enqueue(object : okhttp3.Callback {
        override fun onFailure(call: Call, e: IOException) {
            log("onFailure: $e")
            coroutine.resumeWithException(e)
        }

        override fun onResponse(call: Call, response: Response) {
            log("onResponse: ${response.code}")
            response.body?.let {
                try {
                    coroutine.resume(Banner())
                } catch (e: Exception) {
                    coroutine.resumeWithException(e)
                }
            } ?: coroutine.resumeWithException(NullPointerException("ResponseBody is null."))
        }
    })*/
}

suspend fun test() = suspendCoroutine<Banner> {

}